<template>
    <div class="box">
        <div class="left" v-if="!active.lscre">
            <div class="sensorInfo" v-if="sensorInfo">
                <span>{{ sensorInfo.port }} / {{ sensorInfo.address }}</span>
            </div>
            <div class="waveList" v-if="active.value != 0">
                <eig-tags ref="eigtags" :sensorInfo="sensorInfo" v-if="active.eig" @handleCheckedChange="handleEigChange" />
                <wave-type ref="wavetype" :list="activelist" @handleWave="handleWave" v-if="active.list" />

                <el-radio-group class="group2" v-model="direction" size="small" @change="handleDir" v-if="active.dir && sensorInfo && sensorInfo.characters !== 'a2'">
                    <el-radio-button v-for="item in dirs" :label="item">{{ item.label }}</el-radio-button>
                </el-radio-group>

                <sensor-ano v-if="active.value == 7" :sensorInfo="sensorInfo" :datetime="datetime" :wave_type="wave_type" @setCep="get_cep_select" ref="sensor_ano" />
                <el-button style="width: 60%" v-if="active.value == 8" size="small" type="primary" @click="openRadious">请选择上下区间</el-button>
                <radious ref="radious" v-if="active.value == 8" @sendRadios="sendRadios" />
                <div class="times">
                    <trend
                        ref="trend"
                        v-if="active.table"
                        @handleRowClick="setCurrentRow"
                        @handleSelectionChange="handleSelectionChange"
                        :tableList="tableList"
                        :selection="active.selection"
                        @clearData="clearData"
                        :sensorInfo="sensorInfo"
                    />
                    <div v-else style="width: 220px; height: 100%"></div>
                </div>
            </div>
            <div class="waveList" v-else>
                <mqtt-data :sensorInfo="sensorInfo" ref="mqttData" />
            </div>
        </div>
        <div class="chart" ref="element" @dblclick="addNote">
            <div class="timeBox" v-if="active.value != 0">
                <el-date-picker
                    :type="filterConfig[0].type"
                    :placeholder="filterConfig[0].placeholder"
                    v-model="datetime"
                    @change="eigTimeChange"
                    :picker-options="filterConfig[0].pickerOptions"
                    :clearable="false"
                ></el-date-picker>
                <el-button style="margin-left: 8px" type="primary" size="small" @click="clearData" v-if="active.value != 9">重置图表</el-button>
                <el-button v-if="!active.lscre" type="primary" size="small" @click="() => (showNote = !showNote)">{{ showNote ? '隐藏' : '显示' }}备注</el-button>
                <el-button v-if="active.lscre" type="primary" size="small" @click="openEig">选择指标</el-button>
            </div>
            <div class="tools_item" v-if="active.value == 0 && operate == 1">
                <i class="iconfont icon-tupian" @click="uploadImg" title="上传2.5D设备图片" style="zindex: 99; font-size: 26px"></i>
                <i class="iconfont icon-baocun" @click="saveGraph" title="保存绘图" style="zindex: 99"></i>
            </div>
            <div class="img25D" v-if="active.value == 0">
                <img25D ref="img25D1" @changeGCData="changeGCData" />
                <dimg-list ref="dimglist" @initImg="initImg" />
            </div>
            <coll-chart @setTime="setCurrentRow" ref="collChart" :menulist="menulist" v-if="active.type == 'coll'" :sensorInfo="sensorInfo" @getFilter="getFilter" />
            <coll-chart @setTime="setCurrentRow" ref="collChart1" :menulist="strList" v-if="active.type == 'zhifang'" :sensorInfo="sensorInfo" />
            <mult-chart v-if="active.type == 'mult'" ref="multChart" :mulChart="mulChart" :sensorInfo="sensorInfo" @getFilter="getFilter" />
            <single-chart v-if="active.type == 'single'" ref="singleChart" :sensorInfo="sensorInfo" />
            <mul-eigs v-if="active.type == 'eigs'" ref="mulEigs" />
            <fall-wave v-if="active.type == 'fall'" ref="fallWave" :mulChart="mulChart" :sensorInfo="sensorInfo" />
            <div v-if="showNote && data.note !== undefined">
                <div
                    :style="`word-wrap: break-word;width: 200px;position: absolute;left: ${item.percentageX};top: ${item.percentageY};color: ${item.color};font-size: ${item.size}px`"
                    v-for="item in data.note"
                    :key="item.id"
                    @click="deleteNote(item)"
                >
                    <div>{{ item.writer }}备注:</div>
                    <div>{{ item.content }}</div>
                    <div>{{ item.time }}</div>
                </div>
            </div>
        </div>
        <zy-form ref="zyform" :dialog="dialog" @add="add" />
        <dataFilter ref="dataFilter" @setEigs="setEigs" :sensorInfo="sensorInfo" />
    </div>
</template>
<script>
import { mapState } from 'vuex'
import { requestApi } from '@/requset/api'
import { deepClone } from '@/plugins/clone'
import { nanoid } from 'nanoid'
import { dirs, chartOptions, fallWaveOptions, lineStyle, collList, strList } from '../config'
import waveType from './waveType.vue'
import sensorAno from './sensorAno.vue'
import zyForm from '@/components/common/zyForm.vue'
import trend from './trend.vue'
import collChart from './collChart.vue'
import multChart from './multChart.vue'
import fallWave from './fallWave.vue'
import eigTags from './eigTags.vue'
import mqttData from '@/components/mqttData'
import img25D from '@/components/img25D'
import dimgList from '@/components/dimglist'
import mulEigs from './mulEigs.vue'
import singleChart from './singleChart.vue'
import dataFilter from './dataFilter.vue'
import { filterConfig, dilution, unitsType, multEigs, funOption, typeOption, freOption } from './config'
import radious from './radious.vue'
export default {
    data() {
        return {
            menulist: null,
            strList,
            zhifang: false,
            baseWave: [],
            sensorInfo: {
                address: '',
                port: '',
            },
            multiWave: [],
            multiSpec: [],
            wave_type: null,
            direction: null,
            trend: null, //趋势
            wave: null, //波形
            fre: null, //频谱
            dirs: [],
            tableList: [],
            mulChart: [],
            series3d: [],
            SelectionArr: [],
            preSelectionArr: [],
            eigArr: [],
            data: {},
            preEigArr: [],
            datetime: [new Date().getTime() - 3600 * 1000 * 24 * 7, new Date().getTime()],
            filterConfig: null,
            device_id: null,
            dialog: {
                config: [
                    {
                        name: 'content',
                        type: 'input',
                        label: '标签内容',
                    },
                    {
                        name: 'size',
                        type: 'number',
                        label: '字体大小',
                    },
                    {
                        name: 'color',
                        type: 'color',
                        label: '字体颜色',
                    },
                ],
                form: {
                    content: '',
                    size: 14,
                    color: '#fff',
                    percentageX: '',
                    percentageY: '',
                },
                title: '新增标签',
                labelWidth: '140px',
            },
            showNote: false,
            sensor_ano: [],
            currentRow: null,
            cep_select: null,
            lharr: [0, 0],
            checkSensor: [],
            sensorArr: [],
            preSensorArr: [],
            eigArrs: [],
            seriesArrs: [],
            activelist: [],
        }
    },
    components: {
        waveType,
        trend,
        collChart,
        multChart,
        singleChart,
        eigTags,
        fallWave,
        mqttData,
        img25D,
        zyForm,
        sensorAno,
        radious,
        mulEigs,
        dataFilter,
        dimgList,
    },
    computed: {
        ...mapState('backstage', ['sys_eig']),
    },
    props: {
        active: {
            type: Object,
            default() {
                return {}
            },
        },
    },
    methods: {
        async getFilter(e) {
            let aValue = this.active.value
            if (aValue == 1) {
                this.getWave(this.currentRow, e)
            } else {
                let { id, options, status, fmax, fmin, waveType, fun, specType, type } = e
                let filterTitle = ''
                if (status) {
                    let filterType = typeOption.filter((e) => e.value == type)[0].label

                    filterTitle = `_${filterType}滤波 [${fmin},${fmax}]`
                    options.title.text += ` ${filterTitle}`

                    if (waveType == 'fre') {
                        let fun1 = funOption.filter((e) => e.value == fun)[0].label
                        let specType1 = freOption.filter((e) => e.value == specType)[0].label
                        options.title.text += ` ${fun1}_${specType1}`
                    }
                }
                const aValue = this.active.value
                const { proj_no } = this.sensorInfo
                const { wave_type } = this
                let obj = {
                    proj_no,
                    waveid: id,
                    wave_type: wave_type.value,
                    waveFilter: e,
                }
                if (aValue == 4 || aValue == 5 || aValue == 14) {
                    obj = {
                        proj_no,
                        waveid: id,
                        wave_type: wave_type.value,
                        flag: ['spec'],
                    }
                } else if (aValue == 6) {
                    obj = {
                        proj_no,
                        waveid: id,
                        wave_type: wave_type.value,
                        flag: ['rep'],
                    }
                }
                let res = await requestApi('post', 'diag/wave', obj, false)
                if (res.data.code == 0) {
                    let list = res.data.data
                    let { freq } = list
                    this.wave.freq = freq
                    if (list['wave']) {
                        var data = this.befGetWave(list['wave'], freq)
                    }
                    if (list['spec']) var data_spec = list['spec']
                    if (list['rep']) var data = this.befGetWave(list['rep'], freq)
                    if (aValue == 3) {
                        options.series = [
                            Object.assign(
                                {
                                    data,
                                },
                                lineStyle(),
                            ),
                        ]
                    } else if (aValue == 4 || aValue == 5) {
                        //多频谱
                        options.series = [
                            Object.assign(
                                {
                                    data: data_spec,
                                },
                                lineStyle(),
                            ),
                        ]
                    } else if (aValue == 6) {
                        options.series = [
                            Object.assign(
                                {
                                    data: data,
                                },
                                lineStyle(),
                            ),
                        ]
                    }
                    this.$refs.multChart.draw(options, id)
                    // else if (aValue == 13) {
                    //     this.multiWave.push(
                    //         Object.assign(
                    //             {
                    //                 data,
                    //                 id,
                    //             },
                    //             lineStyle(`${this.sensorInfo.sensor_name}${this.wave_type.label}${refTitle}_${addedItem.time}`),
                    //         ),
                    //     )
                    // } else if (aValue == 14) {
                    //     refTitle = '频谱'
                    //     this.multiSpec.push(
                    //         Object.assign(
                    //             {
                    //                 data: data_spec,
                    //                 id,
                    //             },
                    //             lineStyle(`${this.sensorInfo.sensor_name}${this.wave_type.label}${refTitle}_${addedItem.time}`),
                    //         ),
                    //     )
                    // }
                    // if (aValue == 13 || aValue == 14) {
                    //     options.title.text = ''
                    //     this.$nextTick(() => {
                    //         options.legend.enabled = true
                    //         options.series = aValue == 13 ? this.multiWave : this.multiSpec
                    //         this.$refs.multChart.draw(options, 'chart')
                    //     })
                    // } else {
                    //     options.title.text = `${this.sensorInfo.sensor_name}${this.wave_type.label}${refTitle}_${addedItem.time} 总值：${addedItem.value} ${unit}   采样频率:${freq}`
                    //     this.$nextTick(() => {
                    //         if (aValue == 5) {
                    //             this.$refs.fallWave.drawSingle(options)
                    //             this.$refs.fallWave.draw3d(this.series3d, fallWaveOptions())
                    //             return
                    //         }
                    //         this.$refs.multChart.draw(options, id)
                    //     })
                    // }
                }
            }
        },
        setEigs(e) {
            this.eigArrs = e
            this.clearData()
        },
        changeGCData(e) {
            this.$refs.mqttData.setGCdata(e)
        },
        addNote(event) {
            if (!this.showNote) return
            let element = this.$refs.element
            let rect = element.getBoundingClientRect()
            let offsetX = event.clientX - rect.left
            let offsetY = event.clientY - rect.top
            this.dialog.form.percentageX = (offsetX / rect.width) * 100 + '%'
            this.dialog.form.percentageY = (offsetY / rect.height) * 100 + '%'
            this.$refs.zyform.openDialog('add')
        },
        openEig() {
            this.$refs.dataFilter.doOpen(this.sensorInfo)
        },
        add(data) {
            let d = Object.assign(data, { name: this.data.id, writer: sessionStorage.getItem('nick_name'), time: this.dayjs().format('YYYY-MM-DD HH:mm:ss') })
            requestApi('post', 'diag/addNote', d, false).then((res) => {
                if (res.data.code == 0) {
                    this.$message({
                        type: 'success',
                        message: '添加成功',
                    })
                    this.data.note.push(deepClone(d))
                    this.tableList[this.tableList.findIndex((item) => item.id === this.data.id)] = this.data
                    this.$refs.zyform.closeDialog()
                    this.dialog.form.content = ''
                    this.dialog.form.size = 14
                    this.dialog.form.color = '#fff'
                }
            })
        },
        deleteNote(data) {
            this.$confirm('确定删除本条备注？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    requestApi('post', 'diag/deleteNote', data).then((res) => {
                        if (res.data.code == 0) {
                            this.$message({
                                type: 'success',
                                message: '删除成功',
                            })
                            this.data.note.splice(
                                this.data.note.findIndex((item) => item.id === data.id),
                                1,
                            )
                            this.tableList[this.tableList.findIndex((item) => item.id === this.data.id)] = this.data
                        }
                    })
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除',
                    })
                })
        },
        handleWave(e) {
            let { value } = this.active
            this.wave_type = e
            this.setCollTitle(e)
            this.clearData()
            if (value != 2) {
                this.getTableData()
                return
            }
        },
        handleDir(e) {
            this.clearData()
            this.getTableData()
        },
        setDefaultKey(key) {
            this.$nextTick(() => {
                this.$refs.eigtags.setDefaultKey(key)
            })
        },
        handleActiveChange(e) {
            this.clearData()
            let { value } = e
            this.active = e
            this.getTableData()
            if (value == 1) {
                this.getTrend()
            }
            if (this.active.value == 2) this.setEigtags()
            this.get_env_dem()
            if (value != 10) this.$EventBus.$emit('setTreeCheck', false)
            else this.$EventBus.$emit('setTreeCheck', true)

            if (value == 0) this.initImg()
        },
        //获取表格数据
        getTableData() {
            let eigkey = 'rms'
            this.tableList.splice(0, this.tableList.length)
            if (!this.wave_type) {
                try {
                    this.wave_type = this.active.list[0]
                } catch (error) {
                    return
                }
            }
            if (this.sensorInfo && this.direction && this.wave_type) {
                let a1 = this.getDirAxial(this.sensorInfo.direction)

                let { address, port, proj_no, single } = this.sensorInfo
                let arr1 = this.getChannel(address)
                let obj = {
                    saddr: arr1[0],
                    channel: arr1[1],
                    sport: port,
                    axial: single == 1 ? 'Z' : a1[this.direction.value],
                    proj_no,
                    wave_type: this.wave_type.value,
                    stime: this.dayjs(this.datetime[0]).unix(),
                    etime: this.dayjs(this.datetime[1]).unix(),
                    eigkey: `${this.wave_type.value}_${eigkey}`,
                    multi: this.active.value == 11 ? 1 : '',
                }
                if (this.$refs.trend) {
                    this.collChartLoading('trend')
                    this.$refs.trend.loading = true
                }
                return requestApi('post', 'diag/wave/time', obj, false)
                    .then((res) => {
                        if (res.data.code == 0) {
                            let list = res.data.data
                            if (list.length > 0) {
                                list.forEach((e) => {
                                    let { id } = e
                                    let time = Number(id.split('_')[id.split('_').length - 1])
                                    this.tableList.unshift({
                                        ...e,
                                        time: this.dayjs(time * 1000).format('YYYY/MM/DD HH:mm:ss'),
                                    })
                                })
                                this.data = this.tableList[0]
                            }
                            if (this.active.value == 1 || this.active.value == -1) {
                                this.getTrend()
                            }
                            if (this.active.value == 11) {
                                this.getMultTrend()
                            }
                        }
                    })
                    .finally(() => {
                        if (this.$refs.trend) this.$refs.trend.loading = false
                    })
            }
        },
        getDirAxial(axial) {
            switch (axial) {
                case 'V':
                    return {
                        V: 'Z',
                        A: 'X',
                        H: 'Y',
                    }
                case 'H':
                    return {
                        V: 'X',
                        A: 'Y',
                        H: 'Z',
                    }
                case 'A':
                    return {
                        V: 'X',
                        A: 'Z',
                        H: 'Y',
                    }
            }
        },
        getDirAxialLabel(axial, value) {
            let a = {}
            switch (axial) {
                case 'V':
                    a = {
                        Z: '垂直',
                        X: '轴向',
                        Y: '水平',
                    }
                    break
                case 'H':
                    a = {
                        X: '垂直',
                        Y: '轴向',
                        Z: '水平',
                    }
                    break
                case 'A':
                    a = {
                        X: '垂直',
                        Z: '轴向',
                        Y: '水平',
                    }
                    break
            }
            return a[value]
        },
        //获取趋势图数据
        getTrend() {
            this.$nextTick(() => {
                let { unit } = this.wave_type
                let options = deepClone(chartOptions('datetime', ['', unit]))
                let eigkey = 'rms'
                const arr = []
                this.tableList.forEach((e) => {
                    let { value, time } = e
                    arr.unshift([Number(this.dayjs(time).valueOf()), Number(value.toFixed(3))])
                })
                console.log('趋势图', arr)
                options.title.text = `${this.sensorInfo.sensor_name}${this.wave_type.label}趋势- ${eigkey}`
                options.series = [
                    Object.assign(
                        {
                            data: arr,
                        },
                        lineStyle(),
                    ),
                ]

                this.drawCollChart(options, 'trend')
                if (this.tableList.length > 0) this.setCurrentRow(this.tableList[0])
                else {
                    this.$refs.collChart.clearChart('wave')
                    this.$refs.collChart.clearChart('fre')
                }
            })
        },
        //时域指标多趋势
        getMultTrend() {
            let id = nanoid()
            this.mulChart.unshift({ loading: true, id, type: 'eig' })
            let options = deepClone(chartOptions('datetime'))
            let arr = deepClone(multEigs)
            arr.forEach((item) => {
                item.arr = []
            })
            if (['vel', 'acc'].includes(this.wave_type.value)) {
                options.title.text = `${this.sensorInfo.sensor_name} 时域指标多趋势`
                this.tableList.forEach((e) => {
                    arr.forEach((e2) => {
                        e2.arr.push([Number(this.dayjs(e.time).valueOf()), e[this.wave_type.value + '_' + e2.value]])
                    })
                })
                options.legend.enabled = true
                options.series = arr.map((e) => ({
                    data: e.arr,
                    ...lineStyle(e.name),
                }))
                this.$nextTick(() => {
                    this.$refs.multChart.draw(options, id)
                })
            } else {
                this.$message.info('暂无数据')
                return
            }

            // 更新图表或其他逻辑
            // ...

            // 返回或更新 options 或其他结果
            return options
        },
        getChannel(address) {
            const parts = address.split('_')
            const firstNumber = parts[0]
            const secondNumber = parts[1] ? parts[1] : 0
            return [firstNumber.toString(), secondNumber.toString()]
        },
        //获取波形数据
        getWave(row, waveFilter) {
            let { unit, label } = this.wave_type
            let { selection } = this.active
            if (!selection) {
                let { id, time } = row
                const { proj_no } = this.sensorInfo
                let flag = label.includes('应力波') ? ['spec', 'wave', 'erenges', 'hist'] : ['spec', 'wave']
                let obj = {
                    proj_no,
                    waveid: id,
                    wave_type: this.wave_type.value,
                    flag,
                    waveFilter: waveFilter ? waveFilter : '',
                }
                flag.map((e) => {
                    this.collChartLoading(e)
                })
                this.collChartLoading('fre')

                requestApi('post', 'diag/wave', obj, false).then((res) => {
                    if (res.data.code == 0) {
                        let list = res.data.data
                        let { freq } = list
                        let options = deepClone(chartOptions('linear', ['ms', unit]))
                        this.wave.freq = freq
                        this.wave.time = time
                        this.wave.wave_type = this.wave_type
                        options.wave_type = this.wave_type
                        options.time = time
                        options.freq = freq
                        this.baseWave = list
                        let chartTitle = `${this.sensorInfo.sensor_name}-${this.wave_type.label}波形 - ${time} 采样频率：${freq}`
                        let filterTitle = ''
                        if (obj.waveFilter) {
                            if (obj.waveFilter.status) {
                                let filterType = typeOption.filter((e) => e.value == waveFilter.type)[0].label

                                filterTitle = `_${filterType}滤波 [${waveFilter.fmin},${waveFilter.fmax}]`
                            }
                        }
                        options.title.text = chartTitle + filterTitle
                        const data = this.befGetWave(list['wave'], freq)
                        options.series = [
                            Object.assign(
                                {
                                    data,
                                },
                                lineStyle(),
                            ),
                        ]
                        this.getCep()
                        this.get_env_dem()
                        this.drawCollChart(options, 'wave', freq)
                        this.getFre(row, list['spec'], freq, waveFilter)
                        this.getErenges(row, list['erenges'], freq)
                        this.gethist(row, list['hist'], freq)
                    }
                })
            }
        },
        befGetWave(data, freq) {
            return data
        },
        getFre(row, arr, freq, waveFilter) {
            let { id, time } = row
            let chartTitle = `${this.sensorInfo.sensor_name}-${this.wave_type.label}频谱 ${time} 采样频率：${freq}`
            let filterTitle = ''
            if (waveFilter) {
                let filterType = typeOption.filter((e) => e.value == waveFilter.type)[0].label
                filterTitle = `_${filterType}滤波 [${waveFilter.fmin},${waveFilter.fmax}]`
                if (waveFilter.status && waveFilter.waveType == 'fre') {
                    console.log('waveFilter456456564', waveFilter)
                    let fun = funOption.filter((e) => e.value == waveFilter.fun)[0].label
                    let specType = freOption.filter((e) => e.value == waveFilter.specType)[0].label
                    filterTitle += `_${fun}_${specType}`
                }
            }

            let { unit } = this.wave_type
            let options = deepClone(chartOptions('linear', ['HZ', unit]))
            if (this.wave_type.value == 'vel') arr = arr.filter((e) => e[0] <= 1000)
            options.title.text = chartTitle + filterTitle
            options.series = [
                Object.assign(
                    {
                        data: arr,
                    },
                    lineStyle(),
                ),
            ]
            this.drawCollChart(options, 'fre')
        },
        getErenges(row, arr) {
            if (this.active.value != -1) return
            let { time } = row
            let { unit, label } = this.wave_type
            let options = deepClone(chartOptions('linear', ['ms', unit]))
            options.series = [
                Object.assign(
                    {
                        data: arr,
                    },
                    lineStyle(`${this.sensorInfo.sensor_name}-${this.wave_type.label} 能量图${time} 采样频率 ${freq}`),
                ),
            ]
            // options.title.text = `${this.sensorInfo.sensor_name}-${this.wave_type.label} 能量图${time} 采样频率 ${freq}`
            this.drawCollChart(options, 'erenges')
        },
        gethist(row, arr, freq) {
            if (this.active.value != -1) return
            let { time } = row
            let options = deepClone(chartOptions('column', ['volts', 'count'], 'column'))
            // options.title.text = `${this.sensorInfo.sensor_name}-${this.wave_type.label} 直方图${time} ${freq}`
            options.series = [
                Object.assign(
                    {
                        data: arr.map((e) => e[1]),
                    },
                    lineStyle(`${this.sensorInfo.sensor_name}-${this.wave_type.label} 直方图${time} ${freq}`),
                ),
            ]
            options.xAxis.categories = arr.map((e) => e[0])
            options.type = 'column'
            this.drawCollChart(options, 'hist')
        },
        drawCollChart(options, ref) {
            if (this.active.value == 1) this.$refs.collChart.draw(options, ref)
            if (this.active.value == -1) this.$refs.collChart1.draw(options, ref)
        },
        collChartLoading(ref) {
            if (this.active.value == -1) this.$nextTick(() => this.$refs.collChart1.startLoading(ref))
            if (this.active.value == 1) this.$nextTick(() => this.$refs.collChart.startLoading(ref))
        },
        changeChart(addedItem) {},
        async handleSelectionChange(arr) {
            const addedItem = arr.find((item) => !this.SelectionArr.includes(item))
            const removedItem = this.preSelectionArr.find((item) => !arr.includes(item))
            let { unit } = this.wave_type
            let ref = ''
            let options = deepClone(chartOptions('linear', [unitsType[ref][0], unit]))
            const aValue = this.active.value
            if (addedItem) {
                if (aValue == 3 || aValue == 13)
                    //多时域波形
                    ref = 'wave'
                else if (aValue == 4)
                    //多频谱
                    ref = 'fre'
                else if (aValue == 5) ref = 'fre'
                else if (aValue == 6) ref = 'rep'

                let refTitle = ''
                if (this.mulChart.length >= 8) {
                    this.$refs.trend.toggleRowSelection(arr[arr.length - 1], false)
                    this.$message.info('选择数据过多')
                    return
                }
                let { id, time, value } = addedItem
                const { proj_no } = this.sensorInfo
                const { wave_type } = this
                let obj = {
                    proj_no,
                    waveid: id,
                    wave_type: wave_type.value,
                }
                if (aValue == 4 || aValue == 5 || aValue == 14) {
                    obj = {
                        proj_no,
                        waveid: id,
                        wave_type: wave_type.value,
                        flag: ['spec'],
                    }
                } else if (aValue == 6) {
                    obj = {
                        proj_no,
                        waveid: id,
                        wave_type: wave_type.value,
                        flag: ['rep'],
                    }
                }
                if (aValue == 13 || aValue == 14) {
                    this.mulChart = [
                        {
                            loading: true,
                            id: 'chart',
                            time,
                            value,
                            type: ref,
                        },
                    ]
                } else {
                    this.mulChart.unshift({
                        loading: true,
                        id,
                        time,
                        value,
                        type: ref,
                    })
                }
                let res = await requestApi('post', 'diag/wave', obj, false)
                if (res.data.code == 0) {
                    let list = res.data.data
                    let { freq } = list
                    this.wave.freq = freq
                    if (list['wave']) {
                        var data = this.befGetWave(list['wave'], freq)
                    }
                    if (list['spec']) var data_spec = list['spec']
                    if (list['rep']) var data = this.befGetWave(list['rep'], freq)
                    if (aValue == 3) {
                        options.series = [
                            Object.assign(
                                {
                                    data,
                                },
                                lineStyle(),
                            ),
                        ]
                        refTitle = '波形'
                    } else if (aValue == 4 || aValue == 5) {
                        //多频谱
                        options.series = [
                            Object.assign(
                                {
                                    data: data_spec,
                                },
                                lineStyle(),
                            ),
                        ]
                        refTitle = '频谱'
                        if (aValue == 5) {
                            this.series3d.push({
                                id,
                                type: 'line3D',
                                name: time,
                                lineStyle: {
                                    width: 4,
                                },
                                data: data_spec,
                            })
                        }
                    } else if (aValue == 6) {
                        options.series = [
                            Object.assign(
                                {
                                    data: data,
                                },
                                lineStyle(),
                            ),
                        ]
                        refTitle = '倒谱'
                        unit = 'db'
                    } else if (aValue == 13) {
                        this.multiWave.push(
                            Object.assign(
                                {
                                    data,
                                    id,
                                },
                                lineStyle(`${this.sensorInfo.sensor_name}${this.wave_type.label}${refTitle}_${addedItem.time}`),
                            ),
                        )
                    } else if (aValue == 14) {
                        refTitle = '频谱'
                        this.multiSpec.push(
                            Object.assign(
                                {
                                    data: data_spec,
                                    id,
                                },
                                lineStyle(`${this.sensorInfo.sensor_name}${this.wave_type.label}${refTitle}_${addedItem.time}`),
                            ),
                        )
                    }
                    if (aValue == 13 || aValue == 14) {
                        options.title.text = ''
                        this.$nextTick(() => {
                            options.legend.enabled = true
                            options.series = aValue == 13 ? this.multiWave : this.multiSpec
                            this.$refs.multChart.draw(options, 'chart')
                        })
                    } else {
                        options.title.text = `${this.sensorInfo.sensor_name}${this.wave_type.label}${refTitle}_${addedItem.time} 总值：${addedItem.value} ${unit}   采样频率:${freq}`
                        this.$nextTick(() => {
                            if (aValue == 5) {
                                this.$refs.fallWave.drawSingle(options)
                                this.$refs.fallWave.draw3d(this.series3d, fallWaveOptions())
                                return
                            }
                            this.$refs.multChart.draw(options, id)
                        })
                    }
                }
            }
            if (removedItem) {
                options.legend.enabled = true
                if (aValue == 13) {
                    this.multiWave = this.multiWave.filter((item) => item.id !== removedItem.id)
                    options.series = this.multiWave
                    this.$refs.multChart.draw(options, 'chart')
                } else if (aValue == 14) {
                    this.multiSpec = this.multiSpec.filter((item) => item.id !== removedItem.id)
                    options.series = this.multiSpec
                    this.$refs.multChart.draw(options, 'chart')
                } else {
                    this.mulChart = this.mulChart.filter((item) => item.id !== removedItem.id)
                    this.series3d = this.series3d.filter((item) => item.id !== removedItem.id)
                    if (aValue == 5) this.$refs.fallWave.draw3d(this.series3d, fallWaveOptions())
                }
            }
            this.SelectionArr = arr
            this.preSelectionArr = [...arr]
        },
        handleEigChange(arr) {
            if (this.active.value == 2) {
                let id = nanoid()
                const removedElements = this.preEigArr.find((item) => !arr.includes(item))
                const addedElements = arr.find((item) => !this.eigArr.includes(item))
                if (addedElements) {
                    if (this.mulChart.length >= 8) {
                        this.$message.info('选择数据过多')
                        return
                    }
                    let { nickname, vibration } = addedElements
                    let { address, port, proj_no, single, direction, sensor_name } = this.sensorInfo
                    let arr1 = this.getChannel(address)
                    const obj = {
                        saddr: arr1[0],
                        channel: arr1[1],
                        sport: port,
                        single,
                        proj_no,
                        stime: this.dayjs(this.datetime[0]).unix(),
                        etime: this.dayjs(this.datetime[1]).unix(),
                        eigkey: vibration == 1 ? [nickname] : single == 1 ? [`Z.${nickname}`] : [`Z.${nickname}`, `Y.${nickname}`, `X.${nickname}`],
                        direction,
                        sensor_name,
                    }
                    this.mulChart.push({
                        id,
                        type: 'eig',
                        eigobj: addedElements,
                        loading: true,
                        obj,
                    })
                    this.fetchEigData(id, obj, addedElements)
                }
                if (removedElements) {
                    this.mulChart = this.mulChart.filter((item) => item.eigobj.nickname !== removedElements.nickname)
                }
                this.eigArr = arr
                this.preEigArr = [...arr]
            } else if (this.active.value == 12) {
            }
        },
        //设置 树结构  勾选框
        setCheckSensor(element, ischecked) {
            let id_ = nanoid()
            if (ischecked) {
                if (this.eigArrs.length == 0) {
                    this.$message.info('请选择指标')
                    this.openEig()
                    return
                }
                let { id, address, port, proj_no, single, sensor_name } = element
                this.mulChart.length = 0
                let options = deepClone(chartOptions('datetime'))
                let arr1 = this.getChannel(address)
                const obj = {
                    saddr: arr1[0],
                    channel: arr1[1],
                    sport: port,
                    single,
                    proj_no,
                    stime: this.dayjs(this.datetime[0]).unix(),
                    etime: this.dayjs(this.datetime[1]).unix(),
                }
                this.eigArrs.forEach((eig) => {
                    let arrN = []
                    let arrZ = []
                    let arrX = []
                    let arrY = []
                    let { nickname, vibration, name } = eig
                    obj.eigkey = vibration == 1 ? [nickname] : single == 1 ? [`Z.${nickname}`] : [`Z.${nickname}`, `Y.${nickname}`, `X.${nickname}`]
                    requestApi('post', 'diag/eiges', obj, true).then((res) => {
                        if (res.data.code == 0) {
                            let list = dilution(res.data.data)
                            if (list.length > 0) {
                                list.forEach((e) => {
                                    let { id } = e
                                    var timestamp = Number(id) * 1000
                                    if (vibration == 1) {
                                        arrN.push([timestamp, e[nickname] !== undefined ? e[nickname] : null])
                                    } else if (vibration == 3) {
                                        if (single == 1) arrN.push([timestamp, e['Z'][nickname] !== undefined ? e['Z'][nickname] : null])
                                        else {
                                            try {
                                                arrZ.push([timestamp, e['Z'][nickname] !== undefined ? e['Z'][nickname] : null])
                                                arrX.push([timestamp, e['X'][nickname] !== undefined ? e['X'][nickname] : null])
                                                arrY.push([timestamp, e['Y'][nickname] !== undefined ? e['Y'][nickname] : null])
                                            } catch (error) {
                                                arrZ = arrX = arrY = []
                                            }
                                        }
                                    }
                                })
                            }
                            try {
                                if (arrN.length != 0)
                                    this.seriesArrs.push({
                                        data: arrN,
                                        name: sensor_name + name,
                                        id,
                                    })
                                if (arrX.length != 0)
                                    this.seriesArrs.push({
                                        data: arrX,
                                        name: sensor_name + '轴向' + name,
                                        id,
                                    })
                                if (arrZ.length != 0)
                                    this.seriesArrs.push({
                                        data: arrZ,
                                        name: sensor_name + '垂直' + name,
                                        id,
                                    })
                                if (arrY.length != 0)
                                    this.seriesArrs.push({
                                        data: arrY,
                                        name: sensor_name + '水平' + name,
                                        id,
                                    })
                            } catch (error) {
                                console.log('err', error)
                            }
                            options.series = []
                            this.seriesArrs.forEach((e, i) => {
                                options.series.push(
                                    Object.assign(
                                        {
                                            data: e.data,
                                        },
                                        lineStyle(e.name),
                                    ),
                                )
                            })
                            options.legend.enabled = true
                            options.title.text = ``
                            this.$set(this, 'mulChart', [{ id: id_, type: 'eig', loading: true }])
                            this.$nextTick(() => {
                                this.$refs.multChart.draw(options, id_)
                            })
                        }
                    })
                })
            } else {
                let { id } = element
                this.mulChart.length = 0
                let filteredArr = []
                // 遍历原数组，将 sensor_id 等于 value 的元素加入新数组
                for (let i = 0; i < this.seriesArrs.length; i++) {
                    if (this.seriesArrs[i].id != id) {
                        filteredArr.push(this.seriesArrs[i])
                    }
                }
                // 将新数组赋值给原数组，完成删除操作
                this.seriesArrs = filteredArr

                let options = deepClone(chartOptions('datetime'))
                this.seriesArrs.forEach((e, i) => {
                    options.series.push(
                        Object.assign(
                            {
                                data: e.data,
                            },
                            lineStyle(e.name),
                        ),
                    )
                })
                options.legend.enabled = true
                options.title.text = ``
                this.$set(this, 'mulChart', [{ id: id_, type: 'eig', loading: true }])
                this.$nextTick(() => {
                    this.$refs.multChart.draw(options, id_)
                })
            }
        },
        //修改多个特征值数据
        modifyEig() {
            this.mulChart.forEach((item) => {
                item.loading = true
                let { id, eigobj, obj } = item
                obj.stime = this.dayjs(this.datetime[0]).unix()
                obj.etime = this.dayjs(this.datetime[1]).unix()
                this.fetchEigData(id, obj, eigobj)
            })
        },
        openRadious() {
            this.$refs.radious.doOpen()
        },
        sendRadios(e) {
            this.lharr = e
            this.get_env_dem()
        },
        // 设置高亮行
        setCurrentRow(row) {
            const { time } = row
            this.currentRow = row
            let a1 = this.tableList.find((e) => e.time == time)

            this.data = a1
            this.$refs.trend.setCurrentRow(a1)
            this.getWave(a1)
        },
        //交叉相位
        getCep() {
            if (this.active.value === 7) {
                if (!this.cep_select) {
                    this.$message.info('请选择采样时间')
                    return
                }
                let { id, time } = this.cep_select
                let options1 = deepClone(chartOptions('linear'))
                let options2 = deepClone(chartOptions('linear'))
                this.mulChart.length = 0
                let { proj_no } = this.sensorInfo
                let { wave, freq } = this.baseWave
                let data1 = this.befGetWave(wave, freq).map((e) => e[1])
                requestApi('post', 'diag/wave', { waveid: id, proj_no, wave_type: this.wave_type.value }, true).then((res) => {
                    const { freq, wave } = res.data.data
                    let data2 = this.befGetWave(wave, freq).map((e) => e[1])

                    requestApi('post', 'diag/cep', {
                        data1,
                        data2,
                        freq,
                    }).then((res) => {
                        if (res.data.code == 0) {
                            let { amplitude_spectrum, phase_spectrum } = res.data
                            this.mulChart.unshift({ loading: true, id: this.currentRow.id, type: 'fre' })
                            options1.title.text = `${this.wave_type.label}幅值谱`
                            this.mulChart.unshift({ loading: true, id, type: 'fre' })
                            options2.title.text = `${this.wave_type.label}相位谱`
                            options1.series = [Object.assign({ data: amplitude_spectrum }, lineStyle())]
                            options2.series = [Object.assign({ data: phase_spectrum }, lineStyle())]
                            this.$nextTick(() => {
                                this.$refs.multChart.draw(options1, id)
                                this.$refs.multChart.draw(options2, this.currentRow.id)
                            })
                        }
                    })
                })
            }
        },
        //包络解调
        async get_env_dem() {
            if (this.active.value === 8) {
                if (!this.baseWave) return
                const { spec } = this.baseWave
                let arr = this.lharr
                let options1 = deepClone(chartOptions('linear'))
                let options2 = deepClone(chartOptions('linear'))
                this.mulChart.length = 0
                this.mulChart.push({ loading: true, id: this.currentRow.id, type: 'fre' })
                this.mulChart.push({ loading: true, id: this.currentRow.id + '1', type: 'fre' })
                options1.series = [
                    Object.assign(
                        {
                            data: spec,
                        },
                        lineStyle(`${this.sensorInfo.sensor_name}${this.wave_type.label}频谱_${this.currentRow.time} 总值：${this.currentRow.value} m/s²`),
                    ),
                ]
                // options1.title.text = `${this.sensorInfo.sensor_name}${this.wave_type.label}频谱_${this.currentRow.time} 总值：${this.currentRow.value} m/s²`
                const { proj_no } = this.sensorInfo
                let obj = {
                    waveid: this.currentRow.id,
                    proj_no,
                    wave_type: this.wave_type.value,
                    flag: ['env'],
                    low: arr[0],
                    high: arr[1],
                }
                let res = await requestApi('post', 'diag/wave', obj, false)
                if (res.data.code == 0) {
                    let list = res.data.data
                    let { freq, env } = list
                    options2.series = [
                        Object.assign(
                            {
                                data: env,
                            },
                            lineStyle(`${this.sensorInfo.sensor_name}${this.wave_type.label}包络解调_[${arr[0]} - ${arr[1]}] 采样频率：${freq}`),
                        ),
                    ]

                    this.$nextTick(() => {
                        this.$refs.multChart.draw(options1, this.currentRow.id)
                        this.$refs.multChart.draw(options2, this.currentRow.id + '1')
                    })
                }
            }
        },
        get_cep_select(e) {
            this.cep_select = e
            this.getCep()
        },
        setSensor(newVal, waveTags) {
            let aValue = this.active.value
            if (waveTags.length <= 0) {
                console.log('传感器未配置波形类型')
                return
            }
            this.$set(this, 'activelist', waveTags)
            this.setCollTitle(waveTags[0])
            if (this.$refs.wavetype) this.$refs.wavetype.setDefault(waveTags[0])

            this.$set(this, 'wave_type', this.activelist[0])
            if (aValue == 10) return
            this.sensorInfo = newVal

            let { single, direction } = newVal

            if (single == 1) {
                this.dirs = deepClone(dirs.filter((e) => e.value == direction))
                this.direction = this.dirs[0]
            } else {
                this.dirs = deepClone(dirs)
                this.direction = this.dirs.find((e) => e.value == direction)
            }
            if (aValue != 0) this.getTableData()
            if (aValue == 2) this.setEigtags()
            if (aValue == 9) {
                this.$refs.mulEigs.addSensor(newVal)
            }
            if (aValue == 0) {
                this.initImg()
            }
            if (aValue == 13 || aValue == 14) {
                // this.clearData()
                return
            }
            this.clearData()
        },
        initImg() {
            this.$nextTick(() => this.$refs.img25D1.initImg(this.device_id))
        },
        setCollTitle(e) {
            if (e.label.includes('应力波')) {
                this.$emit('changeZfmenu', true)
            } else {
                this.$emit('changeZfmenu', false)
            }
        },
        setDevice(id) {
            this.device_id = id
        },
        setEigtags() {
            if (this.active.eig) this.$nextTick(() => this.$refs.eigtags.setEigtags(this.sensorInfo))
        },
        fetchEigData(id, obj, addedElements) {
            let Arr = []
            var arrKey = []
            var arrKey1 = []
            var arrKey2 = []
            var arrKey3 = []
            let { nickname, name, unit, vibration } = addedElements
            let { single, direction, sensor_name } = obj
            requestApi('post', 'diag/eiges', obj, false).then((res) => {
                let options = deepClone(chartOptions('datetime'))
                if (res.data.code == 0) {
                    let list = dilution(res.data.data)
                    if (list.length > 0)
                        list.forEach((e) => {
                            let id = e.id
                            if (vibration == 1) {
                                var timestamp = Number(id) * 1000
                                arrKey.push([timestamp, e[nickname] !== undefined ? e[nickname] : null])
                            } else if (vibration == 3) {
                                if (single == 1) {
                                    var timestamp = Number(id) * 1000
                                    arrKey.push([timestamp, e['Z'][nickname] !== undefined ? e['Z'][nickname] : null])
                                } else {
                                    try {
                                        var timestamp = Number(id) * 1000
                                        arrKey1.push([timestamp, e['Z'][nickname] !== undefined ? e['Z'][nickname] : null])
                                        arrKey2.push([timestamp, e['X'][nickname] !== undefined ? e['X'][nickname] : null])
                                        arrKey3.push([timestamp, e['Y'][nickname] !== undefined ? e['Y'][nickname] : null])
                                    } catch {
                                        arrKey1 = arrKey2 = arrKey3 = []
                                    }
                                }
                            }
                        })
                    let names = []

                    if (arrKey.length != 0) {
                        names.push('')
                        Arr.push(arrKey)
                    }
                    if (arrKey1.length != 0) {
                        Arr.push(arrKey1)
                        names.push(this.getDirAxialLabel(direction, 'Z'))
                    }
                    if (arrKey2.length != 0) {
                        Arr.push(arrKey2)
                        names.push(this.getDirAxialLabel(direction, 'X'))
                    }
                    if (arrKey3.length != 0) {
                        Arr.push(arrKey3)
                        names.push(this.getDirAxialLabel(direction, 'Y'))
                    }
                    Arr.forEach((e, i) => {
                        options.series.push(
                            Object.assign(
                                {
                                    data: e,
                                },
                                lineStyle(vibration == 3 ? names[i] + name : name),
                            ),
                        )
                    })
                    options.legend.enabled = true
                    options.title.text = `${sensor_name} -${name} ${unit}`
                }
                this.$nextTick(() => {
                    this.$refs.multChart.draw(options, id)
                })
            })
        },
        eigTimeChange(e) {
            this.datetime = e
            let { value } = this.active
            this.getTableData()
            this.clearData()
            if (value == 2) this.modifyEig()
            if (value == 9) this.$refs.mulEigs.setTime(this.datetime)
        },
        clearData() {
            this.mulChart.splice(0, this.mulChart.length)
            this.series3d.splice(0, this.series3d.length)
            if (this.active.selection) this.$refs.trend.clearAllSelection()
            if (this.active.value == 2) {
                this.eigArr = []
                this.preEigArr = []
                this.$refs.eigtags.clearChecked()
            }
            if (this.active.value == 5) this.$refs.fallWave.clearEcharts()
            if (this.active.value == 7) {
                this.$refs.sensor_ano.clearLabel()
                this.$set(this, 'cep_select', null)
            }
            if (this.active.value == 10) {
                this.seriesArrs = []
                this.$emit('clearAllCheckedNodes')
                this.$forceUpdate()
            }
            if (this.active.value == 0) {
            }
            if (this.active.value == 13) {
                this.multiWave = []
            }
            if (this.active.value == 14) this.multiSpec = []
        },
        uploadImg() {
            if (this.active.value == 0) {
                this.$refs.dimglist.doOpen(this.device_id)
            }
        },
        saveGraph() {
            if (this.active.value == 0) this.$refs.img25D1.saveGraph()
        },
    },
    computed: {
        operate() {
            return parseInt(sessionStorage.getItem('operate')) === 1
        },
    },
    created() {
        this.wave = deepClone(chartOptions('linear'))
        this.fre = deepClone(chartOptions('linear'))
        this.menulist = collList
        this.filterConfig = filterConfig
        let { time } = this.$route.query
        if (time) {
            let time_start = this.dayjs(time).subtract(6, 'hours').valueOf()
            let time_end = this.dayjs(time).add(6, 'hours').valueOf()
            this.$set(this.datetime, 0, new Date(time_start))
            this.$set(this.datetime, 1, new Date(time_end))
        }
    },
}
</script>

<style lang="less" scoped>
.box {
    width: 100%;
    height: 100% !important;
    display: flex;
    justify-content: space-between;

    .left {
        width: 250px !important;
        height: 100%;
        border-right: 1px solid #0e76f1;
        position: relative;
        .sensorInfo {
            width: 100%;
            height: 20px;
            color: #0bccde;
            line-height: 20px;
            text-align: center;
            border-bottom: 2px solid #0f75f0;
            font-weight: bold;
            // background-color: #0F75F0;
        }
        .waveList {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;

            .times {
                width: 100%;
                flex-grow: 2;
                padding: 0 0 10px 0;
                overflow: auto;
            }

            .group2 {
                flex-grow: 0;
                padding: 0 0 10px 10px;
            }
        }
    }

    .chart {
        flex-grow: 1;
        height: calc(100% - 46px);
        // width: calc(100% - 256px);
        position: relative;

        .tools_item {
            float: left;
            display: flex;
            align-items: center;

            padding: 0 10px;
            i {
                font-size: 22px;
                color: #a5bdde;
                cursor: pointer;
                transition: all 0.4s;
            }

            i:hover {
                color: #0cd9e8;
            }
        }

        .img25D {
            width: 90%;
            height: 90%;
            position: absolute;
            left: 5%;
            top: 5%;
        }

        .timeBox {
            height: 46px;
            width: 100%;
            // background-color: #0E76F1;
        }

        .el-collapse {
            width: 100%;
            height: 100%;

            .el-collapse-item {
                .coll {
                    width: 100%;
                    // height: 10vh;
                    background-color: transparent;
                }
            }
        }

        .chart_item {
            float: left;

            // border: 1px solid red;
        }
    }
}
</style>
